<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="generator" content="VuePress 2.0.0-beta.27">
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"><script src="https://at.alicdn.com/t/font_2849934_v6y652peian.js"></script><link href="https://gitee.com/ran_yong/mark-down-table-upload/raw/master/img/20211123222242.png" rel="icon"><link rel="stylesheet" type="text/css" href="//at.alicdn.com/t/font_2970797_5eiedcvhf0a.css"><title>Fastapi学习 | Sakura</title><meta name="description" content="">
    <link rel="preload" href="/assets/js/runtime~app.5b846f34.js" as="script"><link rel="preload" href="/assets/css/styles.f5148030.css" as="style"><link rel="preload" href="/assets/js/452.9ec739fe.js" as="script"><link rel="preload" href="/assets/js/app.05eaf2e4.js" as="script">
    <link rel="stylesheet" href="/assets/css/styles.f5148030.css">
  </head>
  <body>
    <div id="app"><!--[--><!--[--><div class="common" style="--borderRadius:10px;--opacity:1;--fontColor:#2c3e50;--fontFamily:-apple-system;--fitter-blue:1px;"><header style="--borderRadius:10px;--opacity:1;--fontColor:#2c3e50;--fontFamily:-apple-system;--fitter-blue:1px;" class="header-bg-show navbar" id="c-navbar"><div class="toggle-sidebar-button"><svg class="icon" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div><span><a href="/" class=""><img style="border-radius:30px;" class="logo" src="https://gitee.com/ran_yong/mark-down-table-upload/raw/master/img/20211123222242.png" alt="Sakura"><span class="site-name" style="color: #2c3e50;">Sakura</span></a></span><div class="navbar-links-wrapper" style=""><!--[--><!--]--><nav class="navbar-links can-hide"><!--[--><div class="navbar-links-item"><!--[--><span class="aurora-nav-font aurora-navbar-icon"></span><a aria-current="page" href="/Back-end/Fastapi.html#" class="router-link-active router-link-exact-active nav-link nav-link-active" aria-label="面经">面经</a><!--]--></div><div class="navbar-links-item"><div class="dropdown-wrapper"><span class="sakura-html aurora-nav-font aurora-navbar-icon"></span><button class="dropdown-title" type="button" aria-label="前端"><span class="title">前端</span><span class="arrow down"></span></button><button class="mobile-dropdown-title" type="button" aria-label="前端"><span class="title">前端</span><span class="right arrow"></span></button><ul style="display:none;" id="c-nav-dropdown" class="nav-dropdown"><!--[--><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>JavaScript</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Front-end/JavaScript%E8%AF%AD%E6%B3%95%E5%AD%A6%E4%B9%A0.html" class="nav-link" aria-label="JavaScript语言">JavaScript语言</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>TypeScript</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Front-end/TypeScript%E8%AF%AD%E6%B3%95%E5%AD%A6%E4%B9%A0.html" class="nav-link" aria-label="TS语法学习">TS语法学习</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>Vue项目实战</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Front-end/Vue%E9%A1%B9%E7%9B%AE%E5%AE%9E%E6%88%98.html" class="nav-link" aria-label="Vue_shop 项目实战">Vue_shop 项目实战</a><!--]--></li><!--]--></ul><!--]--></li><!--]--></ul></div></div><div class="navbar-links-item"><div class="dropdown-wrapper"><span class="sakura-houduankaifa aurora-nav-font aurora-navbar-icon"></span><button class="dropdown-title" type="button" aria-label="后端"><span class="title">后端</span><span class="arrow down"></span></button><button class="mobile-dropdown-title" type="button" aria-label="后端"><span class="title">后端</span><span class="right arrow"></span></button><ul style="display:none;" id="c-nav-dropdown" class="nav-dropdown"><!--[--><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>Fastapi</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a aria-current="page" href="/Back-end/Fastapi.html" class="router-link-active router-link-exact-active nav-link" aria-label="Fastapi学习">Fastapi学习</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>Python基础</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Back-end/python%E5%9F%BA%E7%A1%80%E5%AD%A6%E4%B9%A0.html" class="nav-link" aria-label="python基础学习">python基础学习</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>Go基础</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Back-end/Go%E5%9F%BA%E7%A1%80%E5%AD%A6%E4%B9%A0.html" class="nav-link" aria-label="Go基础学习">Go基础学习</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>SQL基础</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Back-end/SQL%E5%9F%BA%E7%A1%80%E5%AD%A6%E4%B9%A0.html" class="nav-link" aria-label="SQL基础学习">SQL基础学习</a><!--]--></li><!--]--></ul><!--]--></li><!--]--></ul></div></div><div class="navbar-links-item"><div class="dropdown-wrapper"><span class="sakura-service aurora-nav-font aurora-navbar-icon"></span><button class="dropdown-title" type="button" aria-label="服务端"><span class="title">服务端</span><span class="arrow down"></span></button><button class="mobile-dropdown-title" type="button" aria-label="服务端"><span class="title">服务端</span><span class="right arrow"></span></button><ul style="display:none;" id="c-nav-dropdown" class="nav-dropdown"><!--[--><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>宝塔面板</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Other/WebHook.html" class="nav-link" aria-label="宝塔面板自动同步gitee仓库代码">宝塔面板自动同步gitee仓库代码</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>配置公钥</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Other/%E9%85%8D%E7%BD%AEgitee%E3%80%81github%E5%85%AC%E9%92%A5.html" class="nav-link" aria-label="配置gitee、github公钥">配置gitee、github公钥</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>宝塔配置HTTPS</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Other/%E5%AE%9D%E5%A1%94%E9%85%8D%E7%BD%AEHTTPS.html" class="nav-link" aria-label="如何通过宝塔配置HTTPS网站">如何通过宝塔配置HTTPS网站</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>Node后台运行</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Other/%E5%9C%A8linux%E4%B8%AD%E6%8C%81%E7%BB%AD%E8%BF%90%E8%A1%8CNode.js%E6%96%87%E4%BB%B6.html" class="nav-link" aria-label="在linux中持续运行Node.js文件">在linux中持续运行Node.js文件</a><!--]--></li><!--]--></ul><!--]--></li><li class="dropdown-item"><!--[--><h4 class="dropdown-subtitle"><span>Mac安装Scrcpy投屏软件</span></h4><ul class="dropdown-subitem-wrapper"><!--[--><li class="dropdown-subitem"><!--[--><!----><a href="/Other/Mac%E5%AE%89%E8%A3%85scrcpy%E6%8A%95%E5%B1%8F%E8%BD%AF%E4%BB%B6.html" class="nav-link" aria-label="Mac M1芯 安装scrcpy投屏软件">Mac M1芯 安装scrcpy投屏软件</a><!--]--></li><!--]--></ul><!--]--></li><!--]--></ul></div></div><div class="navbar-links-item"><!--[--><span class="sakura-shijianzhou aurora-nav-font aurora-navbar-icon"></span><a href="/aurora-archive/" class="nav-link nav-link-active" aria-label="时间轴">时间轴</a><!--]--></div><div class="navbar-links-item"><!--[--><span class="sakura-guanyuwomen aurora-nav-font aurora-navbar-icon"></span><a href="/about" class="nav-link nav-link-active" aria-label="关于我">关于我</a><!--]--></div><div class="navbar-links-item"><!--[--><span class="sakura-youlianguanli aurora-nav-font aurora-navbar-icon"></span><a href="/link" class="nav-link nav-link-active" aria-label="友链">友链</a><!--]--></div><div class="navbar-links-item"><!--[--><span class="sakura-biaoqian aurora-nav-font aurora-navbar-icon"></span><a href="/tag" class="nav-link nav-link-active" aria-label="标签">标签</a><!--]--></div><div class="navbar-links-item"><!--[--><span class="sakura-41shuoshuo aurora-nav-font aurora-navbar-icon"></span><a href="/mood" class="nav-link nav-link-active" aria-label="说说">说说</a><!--]--></div><div class="navbar-links-item"><!--[--><span class="sakura-xiangce aurora-nav-font aurora-navbar-icon"></span><a href="/photo" class="nav-link nav-link-active" aria-label="相册">相册</a><!--]--></div><div class="navbar-links-item"><!--[--><span class="sakura-github aurora-nav-font aurora-navbar-icon"></span><a class="nav-link external nav-link-active" href="https://github.com/ranyong1997/sakura-docs" rel="noopener noreferrer" target="_blank" aria-label="Sakura"><!--[--><!--]--> Sakura<!--[--><!--]--></a><!--]--></div><!--]--></nav><!--[--><!--]--><!----><form class="search-box" role="search"><input type="search" autocomplete="off" spellcheck="false" value><!----></form></div></header><!--[--><div id="" class="mobile-sidebar-control"></div><div id="" class="mobileAnimate mobile-sidebar"><!----></div><!--]--><div class="setColor" style="--borderRadius:10px;--fontFamily:-apple-system;--fontColor:#2c3e50;"><div id="setIco" class="setIco bg_color"></div><div class="welcome-parent" id="welcome-parent"><div class="custom-about m-4 p-4 f4 color-shadow-small bg-gray-800-mktg rounded-2 signup-content-container welcome" style="display: none;" id="welcome"><span class="cancel aurora-iconfont-common aurora-style-cancel" id="cancel"></span><h1 class="common-style" id="sr-only-h2"></h1><div class="custom-top custom-common"><div class="custom-top-span custom-common-span"><span class="aurora-iconfont-common aurora-style-img home-welcome-custom-icon"></span>  </div><div class="custom-top-span custom-common-span"><span class="aurora-iconfont-common aurora-style-blur home-welcome-custom-icon"></span>  </div></div><div class="custom-bottom custom-common"><div style="flex:1;" class="custom-bottom-span custom-common-span"><!--[--><li class="custom-li"><span style="background-color: #2c3e50;" data-color="#2c3e50"></span></li><li class="custom-li"><span style="background-color: #42a5f5;" data-color="#42a5f5"></span></li><li class="custom-li"><span style="background-color: #8093f1;" data-color="#8093f1"></span></li><li class="custom-li"><span style="background-color: #FF6EC7;" data-color="#FF6EC7"></span></li><li class="custom-li"><span style="background-color: #FF7F00;" data-color="#FF7F00"></span></li><li class="custom-li"><span style="background-color: #8FBC8F;" data-color="#8FBC8F"></span></li><li class="custom-li"><span style="background-color: #EAADEA;" data-color="#EAADEA"></span></li><li class="custom-li"><span style="background-color: #3299CC;" data-color="#3299CC"></span></li><!--]--></div></div><div class="custom-bottom custom-common"><div style="flex:1;" class="custom-bottom-span custom-common-span"><!--[--><li class="custom-li"><span style="font-family: -apple-system;" data-color="-apple-system">冉</span></li><li class="custom-li"><span style="font-family: hlt;" data-color="hlt">冉</span></li><li class="custom-li"><span style="font-family: tzt;" data-color="tzt">冉</span></li><li class="custom-li"><span style="font-family: sst;" data-color="sst">冉</span></li><li class="custom-li"><span style="font-family: lf;" data-color="lf">冉</span></li><li class="custom-li"><span style="font-family: xsf;" data-color="xsf">冉</span></li><li class="custom-li"><span style="font-family: lsf;" data-color="lsf">冉</span></li><li class="custom-li"><span style="font-family: cgt;" data-color="cgt">冉</span></li><!--]--></div></div><div class="custom-bottom custom-common"><div class="custom-bottom-span custom-common-span"> 圆角 </div><div style="flex:3;" class="custom-bottom-span custom-common-span"><div class="input-range"><div class="input-left"><input autocomplete min="1" max="40" value="10" step="1" type="range"></div><div class="input-right">10</div></div></div></div><div class="custom-bottom custom-common"><div class="custom-bottom-span custom-common-span"> 透明度 </div><div style="flex:3;" class="custom-bottom-span custom-common-span"><div class="input-range"><div class="input-left"><input autocomplete min="0" max="1" value="1" step="0.01" type="range"></div><div class="input-right">1</div></div></div></div></div></div></div><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><div style="--fontColor: #2c3e50; --fontFamily: -apple-system;" class="sidebar-single-enter-animate theme-container"><div class="page-sidebar"><div class="sidebar-single-enter-animate page-top" id="page-top" show-mood-edit="false"><div class="top-mask" style="background-image: url(https://api.ixiaowai.cn/api/api.php?time=-Infinity);"></div><div class="aurora-top-bubble"><div class="aurora-top-bubble-par"><div class="aurora-top-bubble-box" id="aurora-top-bubble-box"></div><canvas class="aurora-top-bubble-canvas" id="aurora-top-bubble-canvas"></canvas></div></div><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><div class="page-record-control"><div class="page-top-record" id="page-top-record"><div class="page-record-bot-common page-record-top"><div class="page-record-top-left page-record-single-common"><span class="aurora-iconfont-common aurora-page-word"></span>  <span class="page-record-single-desc">总字数</span><span>0</span></div><div class="page-record-top-right page-record-single-common"><span class="aurora-iconfont-common aurora-page-time"></span>  <span class="page-record-single-desc">时长</span><span>0</span></div></div><div class="page-record-bot-common page-record-center"><div class="page-record-center-left page-record-single-common"><span class="aurora-iconfont-common aurora-page-comment"></span>  <span class="page-record-single-desc">评论数</span><span id="/Back-end/Fastapi.html" class="waline-comment-count"></span></div><div class="page-record-center-right page-record-single-common"><span class="aurora-iconfont-common aurora-page-read"></span>  <span class="page-record-single-desc">总阅读数</span><span id="/Back-end/Fastapi.html" class="waline-visitor-count"></span></div></div><!----></div></div><div class="top-image" id="top-image"><h1></h1></div></div><div class="content"><div id="article-page-parent" class="article-page-parent-pro article-page-parent"><div class="noShowSidebar page-sidebar-left" id="page-sidebar-left"><!--[--><!--]--><!--[--><!--[--><main style="--borderRadius: 10px;--opacity: 1;" class="page sidebar-single-enter-animate" id="article-page"><!--[--><!--]--><div id="theme-default-content" class="hide-h1-tag theme-default-content pageContent medium-zoom-content"><div class="page-top-share"><div class="page-top-share-next"><div class="poster-share" style="z-index:99;"><div class="poster-button" id="poster-button"><span class="aurora-iconfont-common aurora-poster-ico" data="4">生成海报3</span>  </div></div></div></div><!--[--><h1 id="fastapi学习" tabindex="-1"><a class="header-anchor" href="#fastapi学习" aria-hidden="true">#</a> Fastapi学习</h1><div class="custom-container tip"><p class="custom-container-title">TIP</p><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450524-1537517306.png" data="aurora"> FastAPI 框架，高性能，易于学习，高效编码，生产可用_ 官方文档： <a href="https://fastapi.tiangolo.com/" target="_blank" rel="noopener noreferrer">https://fastapi.tiangolo.com<span><svg class="icon outbound" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewbox="0 0 100 100" width="15" height="15"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path><polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg><!--[--><span class="sr-only">open in new window</span><!--]--></span></a> FastAPI 是一个用于构建 API 的现代、快速（高性能)的 web 框架，使用 Python 3.6+ 并基于标准的 Python 类型提示。 关键特性:</p><ul><li><strong>快速</strong>：可与 <strong>NodeJS</strong> 和 <strong>Go</strong> 比肩的极高性能（归功于 Starlette 和 Pydantic）。<a href="https://fastapi.tiangolo.com/zh/#_11" target="_blank" rel="noopener noreferrer">最快的 Python web 框架之一<span><svg class="icon outbound" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewbox="0 0 100 100" width="15" height="15"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path><polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg><!--[--><span class="sr-only">open in new window</span><!--]--></span></a>。</li><li><strong>高效编码</strong>：提高功能开发速度约 200％ 至 300％。*</li><li><strong>更少 bug</strong>：减少约 40％ 的人为（开发者）导致错误。*</li><li><strong>智能</strong>：极佳的编辑器支持。处处皆可自动补全，减少调试时间。</li><li><strong>简单</strong>：设计的易于使用和学习，阅读文档的时间更短。</li><li><strong>简短</strong>：使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。</li><li><strong>健壮</strong>：生产可用级别的代码。还有自动生成的交互式文档。</li><li><strong>标准化</strong>：基于（并完全兼容）API 的相关开放标准</li></ul><h1 id="安装fastapi" tabindex="-1"><a class="header-anchor" href="#安装fastapi" aria-hidden="true">#</a> 安装FastApi：</h1><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code>pip3 install fastapi
pip3 install unicorn
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><h1 id="开始第一个demo" tabindex="-1"><a class="header-anchor" href="#开始第一个demo" aria-hidden="true">#</a> 开始第一个Demo</h1><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token comment"># 创建一个main.py文件</span>

<span class="token keyword">from</span> typing <span class="token keyword">import</span> Optional

<span class="token keyword">from</span> fastapi <span class="token keyword">import</span> FastAPI

app <span class="token operator">=</span> FastAPI<span class="token punctuation">(</span><span class="token punctuation">)</span>


<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>get</span><span class="token punctuation">(</span><span class="token string">&quot;/&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">read_root</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span><span class="token string">&quot;Hello FastApi&quot;</span><span class="token punctuation">}</span>


<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>get</span><span class="token punctuation">(</span><span class="token string">&quot;/items/{item_id}&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">read_item</span><span class="token punctuation">(</span>item_id<span class="token punctuation">:</span> <span class="token builtin">int</span><span class="token punctuation">,</span> q<span class="token punctuation">:</span> Optional<span class="token punctuation">[</span><span class="token builtin">str</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token boolean">None</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span><span class="token string">&quot;item_id&quot;</span><span class="token punctuation">:</span> item_id<span class="token punctuation">,</span> <span class="token string">&quot;q&quot;</span><span class="token punctuation">:</span> q<span class="token punctuation">}</span>

</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br></div></div><h2 id="运行服务器" tabindex="-1"><a class="header-anchor" href="#运行服务器" aria-hidden="true">#</a> 运行服务器：</h2><h3 id="一、命令运行服务器" tabindex="-1"><a class="header-anchor" href="#一、命令运行服务器" aria-hidden="true">#</a> 一、命令运行服务器：</h3><p>uvicorn main:app --reload --port 8888 # 更改端口号 <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450598-734864684.png" data="aurora"></p><h3 id="二、代码运行服务器调试" tabindex="-1"><a class="header-anchor" href="#二、代码运行服务器调试" aria-hidden="true">#</a> 二、代码运行服务器调试：</h3><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token keyword">if</span> __name__ <span class="token operator">==</span> <span class="token string">&#39;__main__&#39;</span><span class="token punctuation">:</span>
    <span class="token keyword">import</span> uvicorn

    uvicorn<span class="token punctuation">.</span>run<span class="token punctuation">(</span><span class="token string">&quot;main:app&quot;</span><span class="token punctuation">,</span> <span class="token builtin">reload</span><span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">,</span> port<span class="token operator">=</span><span class="token number">5555</span><span class="token punctuation">)</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450681-681889731.png" data="aurora"></p><h2 id="fastapi提供交互式api文档一-这很方便我们管理自己的接口" tabindex="-1"><a class="header-anchor" href="#fastapi提供交互式api文档一-这很方便我们管理自己的接口" aria-hidden="true">#</a> FastApi提供交互式Api文档一：这很方便我们管理自己的接口</h2><p>现在访问 <a href="http://127.0.0.1:8000/docs" target="_blank" rel="noopener noreferrer">http://localhost:8000/docs<span><svg class="icon outbound" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewbox="0 0 100 100" width="15" height="15"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path><polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg><!--[--><span class="sr-only">open in new window</span><!--]--></span></a> 就会生成一个Swagger文档 <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450674-1708206194.png" data="aurora"></p><h2 id="fastapi提供交互式api文档二-这很方便我们管理自己的接口" tabindex="-1"><a class="header-anchor" href="#fastapi提供交互式api文档二-这很方便我们管理自己的接口" aria-hidden="true">#</a> FastApi提供交互式Api文档二：这很方便我们管理自己的接口</h2><p>现在访问 <a href="http://127.0.0.1:8000/redoc" target="_blank" rel="noopener noreferrer">http://127.0.0.1:8000/redoc<span><svg class="icon outbound" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewbox="0 0 100 100" width="15" height="15"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path><polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg><!--[--><span class="sr-only">open in new window</span><!--]--></span></a> 就会生成一个redoc文档 <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450595-1548758824.png" data="aurora"> // todo：fastapi中何时用<strong>Path、Query、Header/Body</strong></p><h2 id="如果你想即「get」又「post」同时请求-你可以这么做" tabindex="-1"><a class="header-anchor" href="#如果你想即「get」又「post」同时请求-你可以这么做" aria-hidden="true">#</a> 如果你想即「get」又「post」同时请求，你可以这么做：</h2><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>api_route</span><span class="token punctuation">(</span><span class="token string">&quot;/login&quot;</span><span class="token punctuation">,</span> methods<span class="token operator">=</span><span class="token punctuation">(</span><span class="token string">&quot;GET&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;POST&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;PUT&quot;</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">login</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token triple-quoted-string string">&quot;&quot;&quot;这是一个登陆接口&quot;&quot;&quot;</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span><span class="token string">&quot;msg&quot;</span><span class="token punctuation">:</span> <span class="token string">&quot;login success&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;code&quot;</span><span class="token punctuation">:</span> <span class="token number">200</span><span class="token punctuation">}</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450547-1245255746.png" data="aurora"></p><h2 id="何时用「form」-何时用「body」-何时用「header」呢" tabindex="-1"><a class="header-anchor" href="#何时用「form」-何时用「body」-何时用「header」呢" aria-hidden="true">#</a> 何时用「Form」，何时用「Body」，何时用「Header」呢</h2><p><strong>如果你你以表单的形式传递数据，那你就应该用「Form」，看一下代码</strong></p><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>post</span><span class="token punctuation">(</span><span class="token string">&quot;/login1&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">login_form</span><span class="token punctuation">(</span>username<span class="token operator">=</span>Form<span class="token punctuation">(</span><span class="token boolean">None</span><span class="token punctuation">)</span><span class="token punctuation">,</span> password<span class="token operator">=</span>Form<span class="token punctuation">(</span><span class="token boolean">None</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span><span class="token string">&quot;username&quot;</span><span class="token punctuation">:</span> username<span class="token punctuation">,</span> <span class="token string">&quot;password&quot;</span><span class="token punctuation">:</span> password<span class="token punctuation">}</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450768-371511405.png" data="aurora"><strong>如果你你以JSON的形式传递数据，那你就应该用「Body」，看一下代码</strong></p><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>post</span><span class="token punctuation">(</span><span class="token string">&quot;/login&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">login</span><span class="token punctuation">(</span>data<span class="token operator">=</span>Body<span class="token punctuation">(</span><span class="token boolean">None</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span><span class="token string">&quot;data&quot;</span><span class="token punctuation">:</span> data<span class="token punctuation">}</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450556-1359851886.png" data="aurora"><strong>如果你你想传递「Header」数据，那你就应该用「Header」，看一下代码</strong></p><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>get</span><span class="token punctuation">(</span><span class="token string">&quot;/user&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">user</span><span class="token punctuation">(</span><span class="token builtin">id</span><span class="token punctuation">,</span> num<span class="token operator">=</span>Header<span class="token punctuation">(</span><span class="token boolean">None</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span><span class="token string">&quot;id&quot;</span><span class="token punctuation">:</span> <span class="token builtin">id</span><span class="token punctuation">,</span> <span class="token string">&quot;num&quot;</span><span class="token punctuation">:</span> num<span class="token punctuation">}</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450550-571388114.png" data="aurora"></p><h2 id="如何定制一个返回信息-看代码" tabindex="-1"><a class="header-anchor" href="#如何定制一个返回信息-看代码" aria-hidden="true">#</a> 如何定制一个返回信息，看代码</h2><p>作用：就是将自己定义好的响应结果返回回来</p><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token keyword">from</span> fastapi <span class="token keyword">import</span> FastAPI
<span class="token keyword">from</span> fastapi<span class="token punctuation">.</span>responses <span class="token keyword">import</span> JSONResponse

app <span class="token operator">=</span> FastAPI<span class="token punctuation">(</span><span class="token punctuation">)</span>


<span class="token decorator annotation punctuation">@app<span class="token punctuation">.</span>get</span><span class="token punctuation">(</span><span class="token string">&quot;/user&quot;</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">user</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">return</span> JSONResponse<span class="token punctuation">(</span>content<span class="token operator">=</span><span class="token punctuation">{</span><span class="token string">&quot;msg&quot;</span><span class="token punctuation">:</span> <span class="token string">&quot;get user&quot;</span><span class="token punctuation">}</span><span class="token punctuation">,</span>   <span class="token comment"># 内容</span>
    status_code<span class="token operator">=</span><span class="token number">202</span><span class="token punctuation">,</span>  <span class="token comment"># 状态码，默认为200</span>
    headers<span class="token operator">=</span><span class="token punctuation">{</span><span class="token string">&quot;a&quot;</span><span class="token punctuation">:</span> <span class="token string">&quot;b&quot;</span><span class="token punctuation">}</span><span class="token punctuation">)</span>


<span class="token keyword">if</span> __name__ <span class="token operator">==</span> <span class="token string">&#39;__main__&#39;</span><span class="token punctuation">:</span>
    <span class="token keyword">import</span> uvicorn

    uvicorn<span class="token punctuation">.</span>run<span class="token punctuation">(</span><span class="token string">&quot;04_response:app&quot;</span><span class="token punctuation">,</span> <span class="token builtin">reload</span><span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450612-949726432.png" data="aurora"></p><h2 id="如何将自己写的html网站动态加载到fastapi-jinja2模板返回html页面" tabindex="-1"><a class="header-anchor" href="#如何将自己写的html网站动态加载到fastapi-jinja2模板返回html页面" aria-hidden="true">#</a> 如何将自己写的html网站动态加载到fastapi（jinja2模板返回Html页面）</h2><h3 id="我们需要安装一些依赖库" tabindex="-1"><a class="header-anchor" href="#我们需要安装一些依赖库" aria-hidden="true">#</a> 我们需要安装一些依赖库</h3><p>1、jinja2 <code>pip install jinjia2 </code> 2、aiofiles <code>pip install aiofiles</code></p><h3 id="废话不多说-看代码" tabindex="-1"><a class="header-anchor" href="#废话不多说-看代码" aria-hidden="true">#</a> 废话不多说，看代码</h3><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token keyword">from</span> fastapi <span class="token keyword">import</span> FastAPI<span class="token punctuation">,</span> Request <span class="token keyword">from</span> fastapi<span class="token punctuation">.</span>templating <span class="token keyword">import</span> Jinja2Templates
<span class="token comment"># 需要进入的库from starlette.staticfiles import StaticFiles</span>
<span class="token comment"># 引入静态文件库app = FastAPI()</span>
<span class="token comment"># 指定静态文件存放路径app.mount(&quot;/page&quot;, StaticFiles(directory=&quot;page&quot;), name=&quot;page&quot;)# 指定html 存放目录template = Jinja2Templates(&quot;page&quot;)@app.get(&quot;/home&quot;)def home (req: Request):    return template.TemplateResponse(&quot;index.html&quot;, context={&quot;request&quot;: req})if __name__ == &#39;__main__&#39;:    import uvicorn    uvicorn.run(&quot;d05_templates:app&quot;, reload=True)</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450617-993969700.png" data="aurora"><strong>如果你的代码中有引入到css样式，你就可以向我这样，你会发现样式就被引入进来了</strong></p><h3 id="如果你想自定义传参进来-你可以试试这样" tabindex="-1"><a class="header-anchor" href="#如果你想自定义传参进来-你可以试试这样" aria-hidden="true">#</a> <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450857-918078377.png" data="aurora">如果你想自定义传参进来，你可以试试这样：</h3><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450927-414337391.png" data="aurora"></p><h3 id="如果你想实现这样的例子" tabindex="-1"><a class="header-anchor" href="#如果你想实现这样的例子" aria-hidden="true">#</a> 如果你想实现这样的例子</h3><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.gif" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450614-453011597.gif" data="aurora"></p><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token comment"># main.pyfrom fastapi import FastAPI, Request, Formfrom fastapi.responses import RedirectResponsefrom fastapi.templating import Jinja2Templatesapp = FastAPI()template = Jinja2Templates(&quot;pages&quot;)todos = [&quot;写博客&quot;, &quot;看电影&quot;, &quot;玩游戏&quot;]@app.get(&quot;/&quot;)async def index(req: Request):    return template.TemplateResponse(&quot;index.html&quot;, context={&quot;request&quot;: req, &quot;todos&quot;: todos})@app.post(&quot;/todo&quot;)async def todo(todo=Form(None)):    &quot;&quot;&quot;处理用户发送过来的 todolist 数据&quot;&quot;&quot;    todos.insert(0, todo)    return RedirectResponse(&#39;/&#39;, status_code=302)if __name__ == &#39;__main__&#39;:    import uvicorn    uvicorn.run(&quot;main:app&quot;, reload=True)</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450629-1438946189.png" data="aurora"> 在这里我说一下为什么要将状态码设置为302，如果你不设置这个status_code，浏览器发送给后端的请求状态码为307，因为307的状态码是不能从post请求跳转到get请求，原因是post请求如果要跳转到get请求不通用，如果想进行跳转，需要将307更改为302。 <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450621-1105676000.png" data="aurora"><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450611-558888954.png" data="aurora"></p><div class="language-html ext-html line-numbers-mode"><pre class="language-html"><code># index.html    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>meta</span> <span class="token attr-name">charset</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>UTF-8<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>title</span><span class="token punctuation">&gt;</span></span>Title<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>title</span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">&gt;</span></span>待办事项<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span><span class="token punctuation">&gt;</span></span>    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>form</span> <span class="token attr-name">action</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>/todo<span class="token punctuation">&quot;</span></span> <span class="token attr-name">method</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>post<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>todo<span class="token punctuation">&quot;</span></span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>text<span class="token punctuation">&quot;</span></span> <span class="token attr-name">placeholder</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>请添加待办事件...<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>submit<span class="token punctuation">&quot;</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">&quot;</span>添加<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span>    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>form</span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>    {% for todo in todos %}    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">&gt;</span></span>{{ todo }}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">&gt;</span></span>    {% endfor %}
</code></pre><div class="line-numbers"><span class="line-number">1</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450752-450565568.png" data="aurora"></p><h2 id="关联数据库-将数据存储化" tabindex="-1"><a class="header-anchor" href="#关联数据库-将数据存储化" aria-hidden="true">#</a> 关联数据库，将数据存储化</h2><h3 id="第一步-我们需要安装依赖库" tabindex="-1"><a class="header-anchor" href="#第一步-我们需要安装依赖库" aria-hidden="true">#</a> 第一步：我们需要安装依赖库</h3><p><code>pip install tortoise-orm</code><code>pip install aiomysq</code></p><h3 id="第二步-电脑需要安装mysql-安装调试过程不在赘述" tabindex="-1"><a class="header-anchor" href="#第二步-电脑需要安装mysql-安装调试过程不在赘述" aria-hidden="true">#</a> 第二步：电脑需要安装mysql，安装调试过程不在赘述</h3><p>以我为例：先创建一个db为fastapi的库</p><div class="language-sql ext-sql line-numbers-mode"><pre class="language-sql"><code><span class="token keyword">create</span> <span class="token keyword">database</span> fastapi<span class="token punctuation">;</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450687-144212385.png" data="aurora"></p><h3 id="第三步-配置数据库" tabindex="-1"><a class="header-anchor" href="#第三步-配置数据库" aria-hidden="true">#</a> 第三步：配置数据库</h3><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token keyword">from</span> tortoise<span class="token punctuation">.</span>contrib<span class="token punctuation">.</span>fastapi <span class="token keyword">import</span> register_tortoise<span class="token comment"># 数据库绑定register_tortoise(app,                  db_url=&quot;mysql://root:Ranyong_520@localhost:3306/fastapi&quot;,                  modules={&quot;models&quot;: []},                  add_exception_handlers=True,                  generate_schemas=True)</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450652-2107100573.png" data="aurora"></p><h3 id="实例一-将数据存储到数据库并返回给前端" tabindex="-1"><a class="header-anchor" href="#实例一-将数据存储到数据库并返回给前端" aria-hidden="true">#</a> 实例一：将数据存储到数据库并返回给前端</h3><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token comment"># d06_templates.pyfrom fastapi import FastAPI, Request, Formfrom fastapi.responses import RedirectResponsefrom fastapi.templating import Jinja2Templatesfrom tortoise.contrib.fastapi import register_tortoisefrom dao.models import Todoapp = FastAPI()template = Jinja2Templates(&quot;pages&quot;)# 数据库绑定register_tortoise(app,                  db_url=&quot;mysql://root:Ranyong_520@localhost:3306/fastapi&quot;,                  modules={&quot;models&quot;: [&#39;dao.models&#39;]},  # 设置模型类                  add_exception_handlers=True,                  generate_schemas=True)@app.get(&quot;/&quot;)async def index(req: Request):    # 从数据库获取 todos 的代码    # ORM,获取所有的 todos    todos = await Todo.all()  # 获取所有的todos    print(todos)    return template.TemplateResponse(&quot;index.html&quot;, context={&quot;request&quot;: req, &quot;todos&quot;: todos})@app.post(&quot;/todo&quot;)async def todo(content=Form(None)):    &quot;&quot;&quot;处理用户发送过来的 todolist 数据&quot;&quot;&quot;    await Todo(content=content).save()    return RedirectResponse(&#39;/&#39;, status_code=302)if __name__ == &#39;__main__&#39;:    import uvicorn    uvicorn.run(&quot;d06_templates:app&quot;, reload=True)</span>
</code></pre><div class="line-numbers"><span class="line-number">1</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450873-851989569.png" data="aurora"> 然后创建一个dao的文件夹里面创建一个models的py文件</p><div class="language-python ext-py line-numbers-mode"><pre class="language-python"><code><span class="token keyword">from</span> tortoise <span class="token keyword">import</span> Model<span class="token punctuation">,</span> fields


<span class="token keyword">class</span> <span class="token class-name">Todo</span><span class="token punctuation">(</span>Model<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token triple-quoted-string string">&quot;&quot;&quot;数据库当中的表 todo&quot;&quot;&quot;</span>
    <span class="token builtin">id</span> <span class="token operator">=</span> fields<span class="token punctuation">.</span>IntField<span class="token punctuation">(</span>pk<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>  <span class="token comment"># id为int类型的 pk:是将id作为主键</span>
    content <span class="token operator">=</span> fields<span class="token punctuation">.</span>CharField<span class="token punctuation">(</span>max_length<span class="token operator">=</span><span class="token number">500</span><span class="token punctuation">)</span>  <span class="token comment"># todo项里面的内容    例如:todos = [&quot;写博客&quot;, &quot;看电影&quot;, &quot;玩游戏&quot;]</span>
    created_at <span class="token operator">=</span> fields<span class="token punctuation">.</span>DatetimeField<span class="token punctuation">(</span>auto_now_add<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>  <span class="token comment"># auto_now_add 当每次插入新数据的时候会引用本地时间</span>
    updated_at <span class="token operator">=</span> fields<span class="token punctuation">.</span>DatetimeField<span class="token punctuation">(</span>auto_now<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>  <span class="token comment"># auto_now 当每次修改数据后会更新本地时间</span>

</code></pre><div class="line-numbers"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450706-526128356.png" data="aurora"> 这时候我们来运行下代码： <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.gif" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450635-1846301692.gif" data="aurora"> 可以发现返回了，并没有返回添加的数据，那我们再去数据库看,点击数据库更新按钮后，可以发现我们的数据已经存储到了表中表。 <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.gif" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450658-625902721.gif" data="aurora"><img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450637-77645872.png" data="aurora"> 可以看到数据库已经存了我们提交的数据，现在我们只需要改一下index.html文件一个地方就可以解决 <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.png" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450635-22672447.png" data="aurora"> 最后效果 <img src="https://ooszy.cco.vin/img/blog-public/ljz.gif" alt="image.gif" originSrc="https://img2020.cnblogs.com/blog/2299022/202107/2299022-20210704210450673-1759991875.gif" data="aurora"></p></div><!--]--></div><footer class="page-meta"><div class="meta-item edit-link"><!--[--><span class="aurora-nav-font aurora-navbar-icon"></span><a class="nav-link external nav-link-active meta-item-label" href="https://github.com/ranyong1997/sakura-docs/edit/main/docs/Back-end/Fastapi.md" rel="noopener noreferrer" target="_blank" aria-label="编辑"><!--[--><!--]--> 编辑<!--[--><!--]--></a><!--]--></div><div class="meta-item last-updated"><span class="meta-item-label">lastTime: </span><span class="meta-item-info">2022/2/21 上午12:15:15</span></div><div class="meta-item contributors"><span class="meta-item-label">Contributors: </span><span class="meta-item-info"><!--[--><!--[--><span class="contributor" title="email: 1311518086@qq.com">冉勇</span><!--[-->, <!--]--><!--]--><!--[--><span class="contributor" title="email: 67427627+ranyong1997@users.noreply.github.com">luck_baby</span><!----><!--]--><!--]--></span></div></footer><!--[--><!--]--></main><main style="--borderRadius:10px;--opacity:1;" class="page box"><div class="theme-default-content"><!--[--><div style="--homePageImgApi:url(https://api.ixiaowai.cn/api/api.php?time=-41400);" class="page-bottom-next"><div class="page-next-left page-next-item"><a aria-current="page" href="/Back-end/Fastapi.html" class="router-link-active router-link-exact-active"><span></span></a></div><!----></div><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--></div></main><div><!----></div><div class="recommend-page"><main style="--borderRadius:10px;--opacity:1;" class="page box"><h2 id="recommend-top-title">推荐阅读</h2><div id="recommend" class="recommend"><!--[--><!--]--></div></main></div><div id="control-comment" class="aurora-control-comment-box"><div style="--borderRadius: 10px;--opacity: 1;" class="theme-comment-box"><span class="aurora-comment-common aurora-iconfont-common page-comment-icon"></span><span class="aurora-comment-common aurora-comment-text">点击评论</span></div><div class="mobile-record aurora-comment-animate"><div class="page box" style="--borderRadius: 10px;--opacity: 1;"><div id="waline" class="vcomment-bottom theme-default-content"></div></div></div></div><!--]--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--></div><div id="page-sidebar-right" style="" class="page-sidebar-right"><div class="stickSidebar"><!--[--><div class="sidebar-cqy"></div><div style="--borderRadius: 10px;--opacity: 1;" id="stickSidebar" class="sidebar-single-enter-animate"><div class="sidebarScroll home-sidebar" style="" id="home-sidebar"><div id="" class="sidebar-single-common"><div class="home-sidebar-avatar"><img id="home-sidebar-avatar-img" src="https://gitee.com/ran_yong/mark-down-table-upload/raw/master/img/20211123222242.png" alt=""></div><div class="home-sidebar-info-desc"><span>Sakura</span></div><div class="home-sidebar-info-page"><div class="sidebar-page-common"><div>文章</div><div>19</div></div><div class="sidebar-page-common"><div>标签</div><div>24</div></div><div class="sidebar-page-common"><div>类别</div><div>4</div></div></div><a target="_blank" href="https://github.com/ranyong1997/sakura-docs"><div class="sidebar-github">Github</div></a><!--[--><!--]--></div><!--[--><!--]--><!----><!--[--><!--]--><div id="" class="sidebar-single-common"><div class="sidebar-link"><!--[--><!--]--></div></div><!----><!--[--><!--]--><!----><!--[--><!--]--><div id="" class="sidebar-single-enter-animate sidebar-single-page sidebar-single-common"><div class="change-page"><div class="catalog-page change-page-common"><span class="changePageActive" index="1">文章目录</span></div><div style="" class="latest-page change-page-common"><!----><span style="" class="" index="2">最新文章</span></div></div><div class="" style=""><!--[--><!--]--></div><div style="display:none;"><!--[--><!--]--></div><!--[--><!--]--></div><!--[--><!--]--><div id="" class="sidebar-single-enter-animate sidebar-single-common"><div class="sidebar-page"><span class="aurora-iconfont-common aurora-sidebar-message"></span><span>公告</span></div><div class="sidebar-message"><!--[--><li id="sidebar-message" class="sidebar-hover-bg-common"><span>这是一个公告<a href="#">Sakura</a></span></li><li id="sidebar-message" class="sidebar-hover-bg-common"><span>祝大家学业进步</span></li><!--]--></div><!--[--><!--]--></div><!--[--><!--]--><div id="" class="sidebar-single-enter-animate sidebar-single-common"><div id="home-tag-sidebar" class="sidebar-page"><span class="aurora-iconfont-common aurora-sidebar-tag"></span><span>标签</span></div><!----><div class="sidebar-tag-item"><!--[--><a href="/tag?tag=Python" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #0fa3b1; font-size: 26px;">Python</span></div></a><a href="/tag?tag=后端" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #fcf6bd; font-size: 28px;">后端</span></div></a><a href="/tag?tag=接口" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #b9faf8; font-size: 14px;">接口</span></div></a><a href="/tag?tag=Go" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #b5e2fa; font-size: 18px;">Go</span></div></a><a href="/tag?tag=数据库" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #ef90b3; font-size: 22px;">数据库</span></div></a><a href="/tag?tag=SQL" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #ff9800; font-size: 11px;">SQL</span></div></a><a href="/tag?tag=Python基础" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #c0d9dd; font-size: 19px;">Python基础</span></div></a><a href="/tag?tag=前端三剑客" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #b39ddb; font-size: 34px;">前端三剑客</span></div></a><a href="/tag?tag=JavaScript" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #d8e2dc; font-size: 27px;">JavaScript</span></div></a><a href="/tag?tag=TypeScript" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #c0d9dd; font-size: 20px;">TypeScript</span></div></a><a href="/tag?tag=Vue" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #42a5f5; font-size: 25px;">Vue</span></div></a><a href="/tag?tag=Element UI" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #fdc5f5; font-size: 10px;">Element UI</span></div></a><a href="/tag?tag=Axios" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #b9faf8; font-size: 33px;">Axios</span></div></a><a href="/tag?tag=Scrcpy" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #bbe6e4; font-size: 32px;">Scrcpy</span></div></a><a href="/tag?tag=投屏软件" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #42a5f5; font-size: 30px;">投屏软件</span></div></a><a href="/tag?tag=宝塔面板" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #fbc4ab; font-size: 17px;">宝塔面板</span></div></a><a href="/tag?tag=同步代码" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #0fa3b1; font-size: 27px;">同步代码</span></div></a><a href="/tag?tag=Node" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #caf0f8; font-size: 33px;">Node</span></div></a><a href="/tag?tag=持续运行" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #ded9e2; font-size: 11px;">持续运行</span></div></a><a href="/tag?tag=HTTPS" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #a9def9; font-size: 26px;">HTTPS</span></div></a><a href="/tag?tag=SSL" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #ffcad4; font-size: 32px;">SSL</span></div></a><a href="/tag?tag=Github" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #5e548e; font-size: 21px;">Github</span></div></a><a href="/tag?tag=Gitee" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #c0d9dd; font-size: 32px;">Gitee</span></div></a><a href="/tag?tag=公钥" class=""><div class="sidebar-tag-single"><span class="home-sidebar-tag-hover" style="color: #b388ff; font-size: 30px;">公钥</span></div></a><!--]--></div><!--[--><!--]--></div><!--[--><!--]--><!----><!--[--><!--]--></div></div><!--]--></div></div></div></div></div><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><!--[--><!--]--><div style="--borderRadius:10px;--opacity:1;--fontColor:#2c3e50;--fontFamily:-apple-system;--fitter-blue:1px;" class="sidebar-single-enter-animate footer-layout-center" data-v-4c868354><div class="footer box" id="footer" data-v-4c868354><!--[--><div class="footer-item" id="footer-item" data-v-4c868354><span>Copyright © by sakura All Rights Reserved.</span></div><div class="footer-item" id="footer-item" data-v-4c868354><span><a target='_blank' href='#' style='display:inline-block;text-decoration:none;height:20px;line-height:20px;'><img src='' style='float:left;'/><p style='float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px;'>💗</p></a></span></div><!--]--><div class="footer-item" id="footer-item" data-v-4c868354><span data-v-4c868354>小破站已运行207天22小时36分1秒</span></div></div></div></div><div id="set-bg" class="set-bg-fitter" style="--opacity: 1; --borderRadius: 10px; --backgroundImageUrl: url()"></div><div id="posterShade" class=""><span class=""></span></div></div><!----><!--]--><!----><div class="no-aurora-music-box aurora-music-box"><div class="music-box"><div class="no-show-more-song music-more"><!--[--><div class="aurora-music-more-single"><span class="aurora-music-song-active aurora-music-font aurora-music-music1 aurora-music-song-info aurora-music-cursor aurora-music-song">SAKURA</span></div><!--]--></div><div class="music-player"><div class="aurora-music-pic-par"><div class="aurora-music-pic" id="aurora-music-pic"><div class="aurora-music-pause"><span class="aurora-music-bofang4 aurora-music-font aurora-music-control-pause aurora-music-cursor"></span></div><img src="/sakura.png" alt=""></div></div><div class="aurora-music-info"><div class="aurora-music-info-left"></div><div class="aurora-music-info-right"><div class="aurora-music-title aurora-music-info-common"><span class="aurora-music-font aurora-music-music1 aurora-music-song-info aurora-music-cursor aurora-music-song">SAKURA</span></div><div class="aurora-music-bottom aurora-music-info-common"><div class="aurora-music-operate"><div><span class="aurora-music-font aurora-music-shangyishou1 aurora-music-cursor"></span></div></div><div class="aurora-music-operate"><div><span class="aurora-music-font aurora-music-xiayishou2 aurora-music-cursor"></span></div></div><div class="aurora-music-operate"><div><span class="aurora-music-geshunxubofang aurora-music-font aurora-music-cursor"></span></div></div><div class="aurora-music-operate"><div><span class="aurora-music-font aurora-music-gengduotianchong aurora-music-cursor aurora-music-operate-more"></span></div></div></div></div></div></div></div><audio autoplay class="aurora-music-player-control" controls="controls"><source src="musicSrc" type="audio/mp3"> Your browser does not support this audio format. </audio></div><div class="aurora-bubble" style="--aurora-bubble-z-index:-2;" data-v-267f56da><div class="aurora-bubble-box" id="aurora-bubble-box" data-v-267f56da></div><canvas class="aurora-bubble-canvas" id="aurora-bubble-canvas" data-v-267f56da></canvas></div><!--]--></div>
    <script src="/assets/js/runtime~app.5b846f34.js" defer></script><script src="/assets/js/452.9ec739fe.js" defer></script><script src="/assets/js/app.05eaf2e4.js" defer></script>
  </body>
</html>
